<template>
  <div :class="{fullscreen:fullscreen}">
    <textarea :id="tinymceId" class="tinymce-textarea" />
  </div>
</template>

<script>

import 'tinymce/tinymce'
import 'tinymce/themes/silver'
import plugins from './plugins'
import toolbar from './toolbar'
const imageUploadUrl = '/support/attachment/uploadImage'
const imageUploadParamsKeys = ['entityId', 'entityType', 'moduleCode']
// const imageBase64 = 'quickbars'
export default {
  props: {
    value: {
      type: String,
      required: false,
      default: ''
    },
    id: {
      type: String,
      default: function () {
        return 'vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '')
      }
    },
    imageUploadParams: {
      type: Object,
      default: () => {
        return {}
      }
    },
    toolbar: {
      type: Array,
      required: false,
      default() {
        return []
      }
    },
    menubar: {
      type: String,
      default: 'file edit insert view format table'
    },
    height: {
      type: [Number, String],
      required: false,
      default: 800
    },
    width: {
      type: [Number, String],
      required: false,
      default: 'auto'
    },
    readonly: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      hasChange: false,
      hasInit: false,
      tinymceObj: null,
      tinymceId: this.id,
      fullscreen: false,
      languageTypeList: {
        'en-us': 'en',
        'zh-cn': 'zh_CN'
      }
    }
  },
  computed: {
    language() {
      // TODO 设置默认为中文
      // return this.languageTypeList[this.$store.getters.language]
      return this.languageTypeList['zh-cn']
    },
    containerWidth() {
      const width = this.width
      if (/^[\d]+(\.[\d]+)?$/.test(width)) { // matches `100`, `'100'`
        return `${width}px`
      }
      return width
    }
  },
  watch: {
    value(val) {
      this.$nextTick(() => {
        if (this.tinymceObj) {
          const inputVal = this.tinymceObj.getContent()
          if (inputVal !== val) {
            this.tinymceObj.setContent(val || '')
          }
        }
      })
      // if (!this.hasChange && this.hasInit) {
      //   this.$nextTick(() => {
      //     if (this.tinymceObj) { this.tinymceObj.setContent(val || '') }
      //   })
      // }
    },
    language() {
      this.destroyTinymce()
      this.$nextTick(() => this.initTinymce())
    }
  },
  mounted() {
    this.initTinymce()
  },
  destroyed() {
    this.destroyTinymce()
  },
  methods: {
    needUpload() {
      if (this.imageUploadParams) {
        const params = Object.keys(this.imageUploadParams)
        const result = this._.intersection(params, imageUploadParamsKeys)
        return result && result.length === 3
      }
      return false
    },
    initTinymce() {
      const tempPlugins = plugins
      const needImageUpload = this.needUpload()
      // if (needImageUpload) {
      //   // 需要url图片方式，去掉base64插入方式
      //   tempPlugins[0] = tempPlugins[0].replace(imageBase64, '')
      // }
      const _this = this
      window.tinymce.init({
        skin_url: '/static/css/tinymce/skins/ui/oxide',
        content_css: '/static/css/tinymce/skins/content/default/content.css',
        language_url: '/static/js/tinymce/langs/zh_CN.js',
        language: _this.language,
        branding: false,
        selector: `#${_this.tinymceId}`,
        height: _this.height,
        width: _this.width,
        plugins: tempPlugins,
        toolbar: _this.toolbar.length > 0 ? _this.toolbar : toolbar,
        menubar: _this.menubar,
        automatic_uploads: false,
        readonly: _this.readonly,
        images_upload_handler: !needImageUpload ? null : function (blobInfo, success, failure) {
          const xhr = new XMLHttpRequest()
          xhr.withCredentials = false
          xhr.open('POST', process.env.VUE_APP_BASE_API + imageUploadUrl)
          xhr.onload = function () {
            if (xhr.status !== 200) {
              failure('HTTP Error: ' + xhr.status)
              return
            }
            const json = JSON.parse(xhr.responseText)
            if (!json) {
              failure(json.message)
              return
            }
            // 获取到的图片地址
            success(process.env.VUE_APP_BASE_API + '/support/attachment/' + json.data + '/getImage')
          }
          const formData = new FormData()
          if (_this.imageUploadParams) {
            for (const param in _this.imageUploadParams) {
              formData.append(param, _this.imageUploadParams[param])
            }
          }
          formData.append('file', blobInfo.blob(), blobInfo.filename())
          xhr.send(formData)
        },
        init_instance_callback: editor => {
          if (_this.value) {
            editor.setContent(_this.value)
          }
          _this.hasInit = true
          editor.on('NodeChange Change KeyUp SetContent', () => {
            _this.hasChange = true
            _this.$emit('input', editor.getContent())
          })
        },
        setup(editor) {
          editor.on('FullscreenStateChanged', (e) => {
            _this.fullscreen = e.state
          })
        }
      })
      _this.tinymceObj = window.tinymce.get(_this.tinymceId)
    },
    destroyTinymce() {
      if (this.tinymceObj) {
        this.tinymceObj.destroy()
      }
    }
  }
}
</script>

